package com.htgd.gardenexpo.controller;

import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.service.*;
import com.htgd.gardenexpo.utils.GetAmazonS3Client;
import com.htgd.gardenexpo.utils.SecurityParameter;
import com.htgd.gardenexpo.utils.TokenUtil;
import com.htgd.gardenexpo.utils.UniteUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.bytebuddy.matcher.CollectionOneToOneMatcher;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.record.DVALRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author ：hejing
 * @date ：Created in 2021/5/24 14:38
 * @description：新闻管理
 * @menu: 新闻管理
 * @modified By：`
 * @version: 1.0
 */
@RestController
@RequestMapping("/api/news")
@Api(tags = "新闻")
public class NewsManagementController {

    @Value("${upload.absolute.url}")
    public String absolute_url;
    @Value("${local.url}")
    public String local_url;

    @Value("${upload.url}")
    public String upload_url;
    @Value("${spring.file-storage.aws-s3[0].bucket-name}")
    public String bucket_name;

    @Autowired
    private FileStorageService fileStorageService;

    @Resource
    private GetAmazonS3Client getAmazonS3Client;

    @Resource
    private GeConNewsService geConNewsService;

    @Resource
    private GeConNewsAccessService geConNewsAccessService;

    @Resource
    private GeConNewsUploadService geConNewsUploadService;

    @Resource
    private GeConNewsFeedbackService geConNewsFeedbackService;

    @Autowired
    private WxUserCollectService wxUserCollectService;


    /**
     * 新增新闻
     */
    @PostMapping(value = "/add")
    @ApiOperation("新增新闻")
    public CommonResult<JSONObject> add(@RequestBody GeConNews geConNews){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            String uploadIds=geConNews.getUploadIds();
            geConNewsService.insert(geConNews);
            if (!uploadIds.equals("")){
                for (String uploadId:uploadIds.split(",")){
                    GeConNewsUpload geConNewsUpload=geConNewsUploadService.queryById(Integer.parseInt(uploadId));
                    geConNewsUpload.setNewId(geConNews.getNewId());
                    geConNewsUploadService.update(geConNewsUpload);
                }
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }

        return result;
    }
    /**
     * 上传图片
     */
/*    @PostMapping(value = "/uploadNewsPhoto")
    public String uploadNewsPhoto(@RequestParam(value = "file") MultipartFile file){
        if (file.isEmpty()) {
            System.out.println("文件为空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = absolute_url; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return local_url+"upload/"+fileName;
    }*/
    /**
     * 上传文件
     */
    @PostMapping(value = "/uploadNewsFile")
    public GeConNewsUpload uploadNewsFile(@RequestParam(value = "file") MultipartFile file){

        GeConNewsUpload geConNewsUpload = new GeConNewsUpload();
        String fileName = file.getOriginalFilename();  // 文件名
        geConNewsUpload.setFilename(fileName);
        FileInfo fileInfo=fileStorageService.of(file)
                .setPlatform("aws-s3-1")
                .setSaveFilename(System.currentTimeMillis()+"/"+file.getOriginalFilename())
                .upload();
        geConNewsUpload.setFilePath(upload_url+fileInfo.getFilename());
        geConNewsUploadService.insert(geConNewsUpload);
        return geConNewsUpload;
    }

    /**
     * 编辑新闻
     */
    @PostMapping(value = "/edit")
    public CommonResult<JSONObject> edit(@RequestBody GeConNews geConNews){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            String uploadIds=geConNews.getUploadIds();
            geConNewsService.update(geConNews);
            if (!uploadIds.equals("")&&uploadIds.contains(",")){
                geConNewsUploadService.deleteByIds(uploadIds.split(","),geConNews.getNewId());
                for (String uploadId:uploadIds.split(",")){
                    GeConNewsUpload geConNewsUpload=geConNewsUploadService.queryById(Integer.parseInt(uploadId));
                    geConNewsUpload.setNewId(geConNews.getNewId());
                    geConNewsUploadService.update(geConNewsUpload);
                }
            }else {
                geConNewsUploadService.deleteByNewId(geConNews.getNewId());
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除新闻
     */
    @PostMapping(value = "/delete")
    @ApiOperation("删除新闻")
    public CommonResult<JSONObject> delete(int newId){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConNewsService.deleteById(newId);
            List<GeConNewsUpload> list=geConNewsUploadService.queryByNewsId(newId);
            for (GeConNewsUpload geConNewsUpload:list){
                String filepath=geConNewsUpload.getFilePath();
                String path=filepath.substring(filepath.indexOf(bucket_name+"/"),filepath.length()-1);
                getAmazonS3Client.delete(path);
            }
            geConNewsUploadService.deleteByNewId(newId);
            geConNewsFeedbackService.deleteById(newId);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 批量删除新闻
     */
//    @PostMapping(value = "/deleteAll")
    public CommonResult<JSONObject> deleteAll(String newIds){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            if (newIds!=null&&!newIds.equals("")){
                for (String promo:newIds.split(",")){
                    int promoId= Integer.parseInt(promo);
                    delete(promoId);
                }
            }

            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 历史新闻检索列表
     */
    @PostMapping(value = "/list")
    @SecurityParameter
    @ApiOperation("历史新闻检索列表")
    public CommonResult<List<GeConNews>> list(@RequestBody PageQuery pageQuery, HttpServletRequest request){
        CommonResult<List<GeConNews>> result = new CommonResult<>();
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        try{
            pageQuery.setPageNum((pageQuery.getPageNum()-1)* pageQuery.getPageSize());
            List<GeConNews> list=geConNewsService.getAllNewsByValue(pageQuery);
            if (list != null && list.size() > 1) {
                for (GeConNews geConNews : list) {
                    Boolean collect = wxUserCollectService.isLike(openId, geConNews.getNewId().toString(),"news");
                    if (collect) {
                        geConNews.setIsLike(true);
                    }else{
                        geConNews.setIsLike(false);
                    }
//                    String content= UniteUtils.stripHtml(geConNews.getNewContent().toString());
//                    if (!content.equals("")){
//                        geConNews.setNewContent(content.substring(0,content.length()>200?200:content.length()));
//                    }else {
//                        geConNews.setNewContent("");
//                    }
                }
            }
            pageQuery.setPageSize(0);
            List<GeConNews> list1=geConNewsService.getAllNewsByValueNoContent(pageQuery);
            result.setCode(200);
            result.setData(list);
            result.setMessage(String.valueOf(list1.size()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 新闻发布
     */
    @GetMapping(value = "/release")
    public CommonResult<JSONObject> release(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 新闻取消发布
     */
    @GetMapping(value = "/unpublish")
    public CommonResult<JSONObject> unpublish(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 新闻排序
     */
    @GetMapping(value = "/sort")
    public CommonResult<List<Map<String,Object>>> sort(){
        CommonResult<List<Map<String, Object>>> result = new CommonResult<>();
        return result;
    }

    /**
     * 新闻置顶
     */
    @GetMapping(value = "/top")
    public CommonResult<JSONObject> top(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 新闻轮播
     */
    @GetMapping(value = "/carousel")
    public CommonResult<JSONObject> carousel(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 新闻审核
     */
    @GetMapping(value = "/review")
    @ApiOperation("新闻审核")
    public CommonResult<JSONObject> review( GeConNews geConNews){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            GeConNews geConNews1=geConNewsService.queryById(geConNews.getNewId());
            geConNews1.setStatus(geConNews.getStatus());
            if (geConNews.getPublisherId()!=null){
                geConNews1.setPublisherId(geConNews.getPublisherId());
            }
            if (geConNews.getAuthUserId()!=null){
                geConNews1.setAuthUserId(geConNews.getAuthUserId());
            }
            String feedback=geConNews.getFeedback();
            geConNews1.setReleasetime(new Date());
            geConNewsService.update(geConNews1);
            if (!feedback.equals("")){
                GeConNewsFeedback geConNewsFeedback=new GeConNewsFeedback();
                geConNewsFeedback.setNewId(geConNews.getNewId());
                geConNewsFeedback.setContent(feedback);
                geConNewsFeedbackService.insert(geConNewsFeedback);
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 审核失败反馈
     */
    @GetMapping(value = "/feedbackInfo")
    public CommonResult<List<GeConNewsFeedback>> feedbackInfo(int newsId){
        CommonResult<List<GeConNewsFeedback>> result = new CommonResult<>();
        try{
            List<GeConNewsFeedback> list=geConNewsFeedbackService.getinfoByNewId(newsId);
            result.setData(list);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }


    /**
     * 新闻轮播列表
     */
    @GetMapping(value = "/carousellist")
    public CommonResult<List<GeConNews>> carousellist(){
        CommonResult<List<GeConNews>> result = new CommonResult<>();
        try{
            List<GeConNews> list=geConNewsService.getAllHomeNews();
            result.setData(list);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }


    /**
     *  新闻详情
     */
    @PostMapping(value = "/details")
    @SecurityParameter
    @ApiOperation("新闻详情")
    public CommonResult<Map<String,Object>> details(@RequestBody String s, HttpServletRequest request){
        CommonResult<Map<String, Object>> result = new CommonResult<>();
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        try{
            boolean flag1 = s.contains("flag");
            Integer newId= JSON.parseObject(s).getInteger("newId");
            if(flag1){
                boolean flag= JSON.parseObject(s).getBoolean("flag");
                if(flag){
                    addAccess(s);
                }
            }
            Map<String, Object> map = new HashMap<>();
            GeConNews geConNews=geConNewsService.queryById(newId);
            geConNews.setHit(geConNews.getHit()+1);
            geConNewsService.update(geConNews);
            Boolean collect = wxUserCollectService.isLike(openId, geConNews.getNewId().toString(),"news");
            if (collect) {
                geConNews.setIsLike(true);
            }else{
                geConNews.setIsLike(false);
            }
            map.put("news",geConNews);
            List<GeConNewsUpload> geConNewsUpload=geConNewsUploadService.queryByNewsId(newId);
            map.put("upload",geConNewsUpload);
            PageQuery pageQuery = new PageQuery();
             pageQuery.setReviewStatus("3");
            pageQuery.setPageSize(0);
            List<GeConNews> nlist=geConNewsService.getAllNewsByValueNoContent(pageQuery);
            List<GeConNews> list = new ArrayList<>();
            for (int i=0;i<nlist.size();i++){
                GeConNews geConNews1=nlist.get(i);
                if (newId==geConNews1.getNewId()){
                    if (nlist.size() >= 3) {
                        if (i < nlist.size() - 3) {
                            if (i != 0) {
                                map.put("up", Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            list.add(Conversion(nlist.get(i + 2)));
                            list.add(Conversion(nlist.get(i + 3)));
                            map.put("more", list);
                        } else if (i == nlist.size() - 3) {
                            if (i != 0) {
                                map.put("up",Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            list.add(Conversion(nlist.get(i + 2)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(0)));
                            }
                            map.put("more", list);
                        } else if (i == nlist.size() - 2) {
                            if (i != 0) {
                                map.put("up", Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(0)));
                                list.add(Conversion(nlist.get(1)));
                            }
                            map.put("more", list);
                        } else if (i == nlist.size() - 1) {
                            if (i != 0) {
                                map.put("up",Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", "");
                            list.add(Conversion(nlist.get(0)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(1)));
                            }
                            map.put("more", list);
                        }
                    } else {
                        if (i == 0 && nlist.size() > 1) {
                            map.put("up", "");
                            map.put("down", Conversion(nlist.get(i + 1)));
                        } else if (i == 0 && nlist.size() == 1) {
                            map.put("up", "");
                            map.put("down", "");
                        } else {
                            map.put("up", Conversion(nlist.get(i - 1)));
                            map.put("down", "");
                        }
                        map.put("more", "");
                    }
                    break;
                }
            }
            result.setData(map);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }


    public GeConNews  Conversion(GeConNews geConNews){
        GeConNews geConNews1=geConNewsService.queryById(geConNews.getNewId());
        String content=UniteUtils.stripHtml(geConNews1.getNewContent().toString());
        if (!content.equals("")){
            geConNews1.setNewContent(content.substring(0,content.length()>200?200:content.length()));
        }else {
            geConNews1.setNewContent("");
        }
        return geConNews1;
    }

    /**
     * 统计新闻点击
     */
    @PostMapping("/addAccess")
    @SecurityParameter
    public CommonResult<JSONObject> addAccess(@RequestBody String s){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            Integer newsId=JSON.parseObject(s).getInteger("newId");
            GeConNewsAccess geConNewsAccess = new GeConNewsAccess();
            geConNewsAccess.setNewsId(newsId);
            geConNewsAccessService.insert(geConNewsAccess);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    @GetMapping("/addHit")
    public CommonResult<JSONObject> addHit(@RequestParam String newId){
        CommonResult<JSONObject> result = new CommonResult<>();
        GeConNewsAccess geConNewsAccess=new GeConNewsAccess();
        geConNewsAccess.setNewsId(Integer.valueOf(newId));
        geConNewsAccessService.insert(geConNewsAccess);
        result.setCode(200);
        result.setMessage("增加成功");
        return result;
    }


}
